using HCore.Unity.Core;
using HCore.Unity.Extension;
using UnityEngine;

namespace HCore.Tests.Runtime.Minesweeper.Scripts
{
    public class MinesweeperGameHandler : MonoBehaviour
    {
        [SerializeField] private GridPrefabVisual GridPrefabVisual;
        private Map mMap;

        private void Awake()
        {
            mMap = new Map(100, 30, 30);
            mMap.OnEntireMapRevealed += OnEntireMapRevealed;
        }

        private void Start()
        {
            GridPrefabVisual.Setup(mMap.GetGrid());
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                var mouseWorldPosition = GameUtils.GetWorldPositionFromScreen().ToVector2();
                var gridType = mMap.RevealGridPosition(mouseWorldPosition);
                if (gridType is GridType.Mine) GameUtils.CreateWorldTextPopup("Game Over!", mouseWorldPosition);
            }

            if (Input.GetMouseButtonDown(1))
            {
                var mouseWorldPosition = GameUtils.GetWorldPositionFromScreen().ToVector2();
                var gridObject = mMap.GetGrid().GetCell(mouseWorldPosition);
                if (gridObject is { Revealed: false }) gridObject.SetFlagged(!gridObject.Flagged());
            }

            if (Input.GetKeyDown(KeyCode.T)) GridPrefabVisual.SetRevealEntireMap(true);
            if (Input.GetKeyUp(KeyCode.T)) GridPrefabVisual.SetRevealEntireMap(false);
        }

        /// <summary>
        ///     翻开了全部的格子，赢了
        /// </summary>
        private void OnEntireMapRevealed()
        {
            GameDebug.TextPopupMouse("Game Win!");
        }
    }
}